<?php
/*******************************************************************************
 * $Date:: Jan 10, 2011 10:20:33 PM                                            $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * Description here...
 * 
 * @package Lua
 * @subpackage ##Subpackage##
 * @author Tuan Duong <bacduong[at]gmail[dot]com>
 * @version 
 */

class Lua_Service_User implements Lua_Service_Interface
{
    /**
     * @var Lua_Table_User
     */
    private $userTable = null;
    
    /**
     * @var Lua_Table_Group
     */
    private $userGroupTable = null;
    public function __construct()
    {
        $this->userTable = new Lua_Table_User();
        $this->userGroupTable = new Lua_Table_UserGroup();
    }
    
    /**
     * Get all groupIds of user
     * @param int $userId
     * @return array
     */
    public function getGroupIds($userId)
    {
        $baseTable = new Lua_Table_Base();
        $select = $this->userTable->select(true)->setIntegrityCheck(false)->reset();
        $select->from(array('ug' => 'ipoo_user_group'));
        $select->joinInner(array('u' => 'ipoo_user'), "ug.user_id = u.id", array());
        $select->where('u.status = ?', 0);
        $select->where('u.id = ?', $userId);
        $rows = $baseTable->findAll('ipoo_user_group', $select);

        $groupIds = array();
        foreach ($rows as $row) {
            $groupIds[] = $row['group_id'];            
        }
        
        return $groupIds;
    }
    
    public function getUserSelect(array $params = array())
    {
        $select = $this->userTable->select(true)->setIntegrityCheck(false);
        $dir = 'ASC';
        $sort = 'id';
        if (isset($params['dir'])) {
            $dir = $params['dir'];
        }
        
        if (isset($params['sort'])) {
            $sort = $params['sort'];
        }
        $select->order($sort . ' ' . $dir);
        return $select;
    }
    
    /**
     * 
     * Insert into ipoo_user table
     * @param array $params
     * @return id of inserted user
     */
    public function addUser($ipooUser, array $groupIds) {
    	$ipooUser->password = Lua_Crypt::factory()->encrypt($ipooUser->password);
    	$userId = $this->userTable->insert($ipooUser->toArray());
    	foreach ($groupIds as $groupId) {
    		$userGroupParams = array('user_id' => $userId, 'group_id' => $groupId);
    		$this->userGroupTable->insert($userGroupParams);
    	}
    	
    	return $userId;
    }
    
    /**
     * 
     * Update one row in ipoo_user table
     * @param array $params
     *        array $groupIds
     */
    public function updateUser(array $params, array $groupIds) {
    	$userGroupTable = new Lua_Table_UserGroup();
    	$whereDelete = $userGroupTable->getAdapter()->quoteInto('user_id = ?', $params["id"]);
		$userGroupTable->delete($whereDelete);
		
		$whereUpdate = $this->userTable->getAdapter()->quoteInto('id = ?', $params["id"]);
    	$userId = $this->userTable->update($params, $whereUpdate);
    	foreach ($groupIds as $groupId) {
    		$userGroupParams = array('user_id' => $params["id"], 'group_id' => $groupId);
    		$this->userGroupTable->insert($userGroupParams);
    	}
    	
    	return $userId;
    }
    
    
     public function deleteUser($id) {
    	$userGroupTable = new Lua_Table_UserGroup();
    	$whereGroupUser = $userGroupTable->getAdapter()->quoteInto('user_id = ?', $id);
		$userGroupTable->delete($whereGroupUser);

		$whereUser = $this->userTable->getAdapter()->quoteInto('id = ?', $id);
    	$this->userTable->delete($whereUser);
    }
    
    public function findUserByProperty($columnName, $value) {
        $baseTable = new Lua_Table_Base();
        $select = $this->userTable->select(true)->setIntegrityCheck(false)->reset();
        $select->where($columnName.'=?', $value);
        $rows = $baseTable->findAll('ipoo_user', $select);
        return $rows;
    }
    
    
 	public function validateAddUser($ipooUser) {
 		$errors = array();
 		$username = $ipooUser->username;
 		$email = $ipooUser->email;
 		$existingUsers = $this->findUserByProperty('username', $username);
 		if (sizeof($existingUsers)) {
 			$errors["username"] = Lua_Constant_Error::DUPLICATED_ERROR; 	
 		}
 		$existingUsers = $this->findUserByProperty('email', $email);
 	 	if (sizeof($existingUsers)) {
 			$errors["email"] = Lua_Constant_Error::DUPLICATED_ERROR;
 		}
 		return $errors;
 	}
 	
 	public function validateUpdateContactRequest($ipooUser) {
 		$errors = array();
 		return $errors;
 	}
 	
    function updateAvatar () {
 		$auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $userId = $identity->id;
            
            $avatarFile = $_FILES["avatar"];
            $avatarPhotoPath = $this->buildAvatarPhotoPath($userId, $avatarFile);
            
            move_uploaded_file($_FILES["avatar"]["tmp_name"], $avatarPhotoPath);
            
            $existingUser = $this->findUserByProperty("id", $userId);
            $existingUser = $existingUser[0];
            
          
            $existingUser['avatar_photo'] = $avatarPhotoPath;
            
            $whereUser = $this->userTable->getAdapter()->quoteInto('id = ?', $userId);
            $this->userTable->update($existingUser, $whereUser);
        } 
    }
    
    public function validateUpdateAvatar($avatarFile) {
    	$errors = array();
    	$maxFileSize = 1024*1024;//1MB
    	$uploadedFileType = strtolower($avatarFile["type"]);
    	$isValidFileType = $uploadedFileType == "image/jpeg" ||
    		   			   $uploadedFileType == "image/gif" ||
    		   			   $uploadedFileType == "image/png" ||
    		   			   $uploadedFileType == "image/bmp";
   		
    	if ($avatarFile["error"] > 0) {
   			$errors["avatar"][Lua_Constant_Error::UPLOAD_FAILED] = Lua_Constant_Error::UPLOAD_FAILED;
   		}
   		
   		if ($avatarFile["size"] > $maxFileSize) {
   			$errors["avatar"][Lua_Constant_Error::MAX_FILE_SIZE_EXEED] = Lua_Constant_Error::MAX_FILE_SIZE_EXEED;
   		}
   		
       	if (!$isValidFileType) {
   			$errors["avatar"][Lua_Constant_Error::INVALID_FILE_TYPE] = Lua_Constant_Error::INVALID_FILE_TYPE;
   		}
   		return $errors;
    }
 	
 	public function buildAvatarPhotoPath($userId, $avatarFile) {
 		return "images/avatar/".$userId."_".$avatarFile["name"];
 	}
 	
 	
 	public function changePass($newPassword) {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $userId = $identity->id;
            $existingUser = $this->findUserByProperty("id", $userId);
            $existingUser = $existingUser[0];
            $existingUser['password'] = Lua_Crypt::factory()->encrypt($newPassword);
            $whereUser = $this->userTable->getAdapter()->quoteInto('id = ?', $userId);
            $this->userTable->update($existingUser, $whereUser);
        } 
 	}
 	
 	public function validateChangePass($oldPassword, $newPassword) {
 		$errors = array();
 		$auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $userId = $identity->id;
            $existingUser = $this->findUserByProperty("id", $userId);
            $existingUser = $existingUser[0];
            if ($existingUser['password'] != Lua_Crypt::factory()->encrypt($oldPassword)) {
            	$errors["password"] = Lua_Constant_Error::INCORRECT_ERROR;
            }
	        if (strlen($newPassword) < 6) {
	 			$errors["new_password"] = Lua_Constant_Error::LENGTH_TOO_SHORT_ERROR;
	 		}
        } else {
        	$errors["login"] = Lua_Constant_Error::NOT_LOGINED_ERROR;
        }
 		
 		return $errors;
 	}
 	
 	public function updateContact($ipooUser) {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
            $userId = $identity->id;
            $existingUser = $this->findUserByProperty("id", $userId);
            $existingUser = $existingUser[0];
            $existingUser['self_introduce'] = $ipooUser->self_introduce;
            $existingUser['econtact'] = $this->buildEcontactValue();
            $whereUser = $this->userTable->getAdapter()->quoteInto('id = ?', $userId);
            $this->userTable->update($existingUser, $whereUser);
        } 
 	}
 	
 	private function buildEcontactValue() {
 		$econtactValue = '';
 		if (isset($_REQUEST['email'])) {
 			$econtactValue = $econtactValue.'[EMAIL:'.$_REQUEST['email'].']';
 		}
 		if (isset($_REQUEST['facebook'])) {
 			$econtactValue = $econtactValue.'[FACEBOOK:'.$_REQUEST['facebook'].']';
 		}
 		if (isset($_REQUEST['tiwtter'])) {
 			$econtactValue = $econtactValue.'[TIWTTER:'.$_REQUEST['tiwtter'].']';
 		}
		if (isset($_REQUEST['yahoo'])) { 		
 			$econtactValue = $econtactValue.'[YAHOO:'.$_REQUEST['yahoo'].']';
		}
		
		if (isset($_REQUEST['skype'])) {
 			$econtactValue = $econtactValue.'[SKYPE:'.$_REQUEST['skype'].']';
		}
		if (isset($_REQUEST['gplus'])) {
 			$econtactValue = $econtactValue.'[GPLUS:'.$_REQUEST['gplus'].']'; 
		}
 		return $econtactValue;
 	}
 	
 	/**
 	 * 
 	 * Convert econtact string to array.
 	 * Sample econtact input parameter:
 	 * 		[EMAIL:kevin@yahoo.com][FACEBOOK:kevin][TIWTTER:kevintw][YAHOO:kevinym][SKYPE:kevinskype][GPLUS:kevingplus]
 	 * @param String $econtact
 	 * @return array of contact elements.
 	 *  	Sample of return array:
 	 *  	[EMAIL] => kevin@yahoo.com
 	 *  	[FACEBOOK] => kevin
 	 *  	[TIWTTER] => kevintw
 	 *  	[YAHOO] => kevinym
 	 *  	[SKYPE] => kevinskype
 	 *  	[GPLUS] => kevingplus
 	 *  
 	 */
 	public function parseEcontactToArray($econtact) {
		$econtactArr = array();
		$start = 0;
		while($start !== false) {
			$start = strpos($econtact, '[', $start);
			if ($start !== false) {
				$end = strpos($econtact, ']', $start);
				if ($end !== false) {
					$element =  explode(':', substr($econtact, $start + 1, $end - $start - 1));
					if (sizeof($element) == 2) {
						$econtactArr[$element[0]] = $element[1];
					}
					$start = $end + 1;
					$end = $end + 1;
				} else {
					break;
				}
			} else {
				break;
			}
		}
		return $econtactArr;
 	}

}